## @file
# Routines for generating AutoGen.h and AutoGen.c
#
# Copyright (c) 2007 - 2010, Intel Corporation
# All rights reserved. This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution.  The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#

## Import Modules
#
import string

from Common import EdkLogger

from Common.BuildToolError import *
from Common.DataType import *
from Common.Misc import *
from Common.String import StringToArray
from StrGather import *

## PCD type string
gItemTypeStringDatabase  = {
    TAB_PCDS_FEATURE_FLAG       :   'FixedAtBuild',
    TAB_PCDS_FIXED_AT_BUILD     :   'FixedAtBuild',
    TAB_PCDS_PATCHABLE_IN_MODULE:   'BinaryPatch',
    TAB_PCDS_DYNAMIC            :   '',
    TAB_PCDS_DYNAMIC_DEFAULT    :   '',
    TAB_PCDS_DYNAMIC_VPD        :   '',
    TAB_PCDS_DYNAMIC_HII        :   '',
    TAB_PCDS_DYNAMIC_EX         :   '',
    TAB_PCDS_DYNAMIC_EX_DEFAULT :   '',
    TAB_PCDS_DYNAMIC_EX_VPD     :   '',
    TAB_PCDS_DYNAMIC_EX_HII     :   '',
}

## Dynamic PCD types
gDynamicPcd = [TAB_PCDS_DYNAMIC, TAB_PCDS_DYNAMIC_DEFAULT, TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_HII]

## Dynamic-ex PCD types
gDynamicExPcd = [TAB_PCDS_DYNAMIC_EX, TAB_PCDS_DYNAMIC_EX_DEFAULT, TAB_PCDS_DYNAMIC_EX_VPD, TAB_PCDS_DYNAMIC_EX_HII]

## Datum size
gDatumSizeStringDatabase = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOLEAN','VOID*':'8'}
gDatumSizeStringDatabaseH = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'BOOL','VOID*':'PTR'}
gDatumSizeStringDatabaseLib = {'UINT8':'8','UINT16':'16','UINT32':'32','UINT64':'64','BOOLEAN':'Bool','VOID*':'Ptr'}

## Mapping between PCD driver type and EFI phase
gPcdPhaseMap = {
    "PEI_PCD_DRIVER"    :   "PEI",
    "DXE_PCD_DRIVER"    :   "DXE"
}

gPcdDatabaseCommonAutoGenH = """
//
// The following definition will be generated by build tool
//

//
// Common definitions
//
typedef UINT8 SKU_ID;

#define PCD_TYPE_SHIFT        28

#define PCD_TYPE_DATA         (0x0 << PCD_TYPE_SHIFT)
#define PCD_TYPE_HII          (0x8 << PCD_TYPE_SHIFT)
#define PCD_TYPE_VPD          (0x4 << PCD_TYPE_SHIFT)
#define PCD_TYPE_SKU_ENABLED  (0x2 << PCD_TYPE_SHIFT)
#define PCD_TYPE_STRING       (0x1 << PCD_TYPE_SHIFT)

#define PCD_TYPE_ALL_SET      (PCD_TYPE_DATA | PCD_TYPE_HII | PCD_TYPE_VPD | PCD_TYPE_SKU_ENABLED | PCD_TYPE_STRING)

#define PCD_DATUM_TYPE_SHIFT  24

#define PCD_DATUM_TYPE_POINTER  (0x0 << PCD_DATUM_TYPE_SHIFT)
#define PCD_DATUM_TYPE_UINT8    (0x1 << PCD_DATUM_TYPE_SHIFT)
#define PCD_DATUM_TYPE_UINT16   (0x2 << PCD_DATUM_TYPE_SHIFT)
#define PCD_DATUM_TYPE_UINT32   (0x4 << PCD_DATUM_TYPE_SHIFT)
#define PCD_DATUM_TYPE_UINT64   (0x8 << PCD_DATUM_TYPE_SHIFT)

#define PCD_DATUM_TYPE_ALL_SET  (PCD_DATUM_TYPE_POINTER | \\
                                 PCD_DATUM_TYPE_UINT8   | \\
                                 PCD_DATUM_TYPE_UINT16  | \\
                                 PCD_DATUM_TYPE_UINT32  | \\
                                 PCD_DATUM_TYPE_UINT64)

#define PCD_DATABASE_OFFSET_MASK (~(PCD_TYPE_ALL_SET | PCD_DATUM_TYPE_ALL_SET))

typedef struct  {
  UINT32  ExTokenNumber;
  UINT16  LocalTokenNumber;   // PCD Number of this particular platform build
  UINT16  ExGuidIndex;        // Index of GuidTable
} DYNAMICEX_MAPPING;

typedef struct {
  UINT32  SkuDataStartOffset; //We have to use offsetof MACRO as we don't know padding done by compiler
  UINT32  SkuIdTableOffset;   //Offset from the PCD_DB
} SKU_HEAD;

typedef struct {
  UINT16  GuidTableIndex;     // Offset in Guid Table in units of GUID.
  UINT16  StringIndex;        // Offset in String Table in units of UINT16.
  UINT16  Offset;             // Offset in Variable
  UINT16  DefaultValueOffset; // Offset of the Default Value
} VARIABLE_HEAD;

typedef  struct {
  UINT32  Offset;
} VPD_HEAD;

typedef UINT16 STRING_HEAD;

typedef UINT16 SIZE_INFO;

#define offsetof(s,m)  (UINT32) (UINTN) &(((s *)0)->m)

"""

gPcdDatabaseEpilogueAutoGenH = """
typedef struct {
  PEI_PCD_DATABASE PeiDb;
  DXE_PCD_DATABASE DxeDb;
} PCD_DATABASE;

#define PCD_TOTAL_TOKEN_NUMBER (PEI_LOCAL_TOKEN_NUMBER + DXE_LOCAL_TOKEN_NUMBER)

"""

gPcdDatabaseAutoGenH = TemplateString("""
#define ${PHASE}_GUID_TABLE_SIZE                ${GUID_TABLE_SIZE}
#define ${PHASE}_STRING_TABLE_SIZE              ${STRING_TABLE_SIZE}
#define ${PHASE}_SKUID_TABLE_SIZE               ${SKUID_TABLE_SIZE}
#define ${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE  ${LOCAL_TOKEN_NUMBER_TABLE_SIZE}
#define ${PHASE}_LOCAL_TOKEN_NUMBER             ${LOCAL_TOKEN_NUMBER}
#define ${PHASE}_EXMAPPING_TABLE_SIZE           ${EXMAPPING_TABLE_SIZE}
#define ${PHASE}_EX_TOKEN_NUMBER                ${EX_TOKEN_NUMBER}
#define ${PHASE}_SIZE_TABLE_SIZE                ${SIZE_TABLE_SIZE}
#define ${PHASE}_GUID_TABLE_EMPTY               ${GUID_TABLE_EMPTY}
#define ${PHASE}_STRING_TABLE_EMPTY             ${STRING_TABLE_EMPTY}
#define ${PHASE}_SKUID_TABLE_EMPTY              ${SKUID_TABLE_EMPTY}
#define ${PHASE}_DATABASE_EMPTY                 ${DATABASE_EMPTY}
#define ${PHASE}_EXMAP_TABLE_EMPTY              ${EXMAP_TABLE_EMPTY}

typedef struct {
${BEGIN}  UINT64             ${INIT_CNAME_DECL_UINT64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}];
${END}
${BEGIN}  UINT64             ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64};
${END}
${BEGIN}  UINT32             ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}];
${END}
${BEGIN}  UINT32             ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32};
${END}
${BEGIN}  VPD_HEAD           ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}];
${END}
  DYNAMICEX_MAPPING  ExMapTable[${PHASE}_EXMAPPING_TABLE_SIZE];
  UINT32             LocalTokenNumberTable[${PHASE}_LOCAL_TOKEN_NUMBER_TABLE_SIZE];
  GUID               GuidTable[${PHASE}_GUID_TABLE_SIZE];
${BEGIN}  STRING_HEAD        ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}];
${END}
${BEGIN}  VARIABLE_HEAD      ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}_Variable_Header[${VARIABLE_HEAD_NUMSKUS_DECL}];
${END}
${BEGIN}  UINT8              StringTable${STRING_TABLE_INDEX}[${STRING_TABLE_LENGTH}]; /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
${END}
  SIZE_INFO          SizeTable[${PHASE}_SIZE_TABLE_SIZE];
${BEGIN}  UINT16             ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}];
${END}
${BEGIN}  UINT16             ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16};
${END}
${BEGIN}  UINT8              ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}];
${END}
${BEGIN}  UINT8              ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8};
${END}
${BEGIN}  BOOLEAN            ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_DECL_BOOLEAN}];
${END}
${BEGIN}  BOOLEAN            ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN};
${END}
  UINT8              SkuIdTable[${PHASE}_SKUID_TABLE_SIZE];
${SYSTEM_SKU_ID}
} ${PHASE}_PCD_DATABASE_INIT;

typedef struct {
${PCD_DATABASE_UNINIT_EMPTY}
${BEGIN}  UINT64   ${UNINIT_CNAME_DECL_UINT64}_${UNINIT_GUID_DECL_UINT64}[${UNINIT_NUMSKUS_DECL_UINT64}];
${END}
${BEGIN}  UINT32   ${UNINIT_CNAME_DECL_UINT32}_${UNINIT_GUID_DECL_UINT32}[${UNINIT_NUMSKUS_DECL_UINT32}];
${END}
${BEGIN}  UINT16   ${UNINIT_CNAME_DECL_UINT16}_${UNINIT_GUID_DECL_UINT16}[${UNINIT_NUMSKUS_DECL_UINT16}];
${END}
${BEGIN}  UINT8    ${UNINIT_CNAME_DECL_UINT8}_${UNINIT_GUID_DECL_UINT8}[${UNINIT_NUMSKUS_DECL_UINT8}];
${END}
${BEGIN}  BOOLEAN  ${UNINIT_CNAME_DECL_BOOLEAN}_${UNINIT_GUID_DECL_BOOLEAN}[${UNINIT_NUMSKUS_DECL_BOOLEAN}];
${END}
} ${PHASE}_PCD_DATABASE_UNINIT;

#define PCD_${PHASE}_SERVICE_DRIVER_VERSION         2

typedef struct {
  ${PHASE}_PCD_DATABASE_INIT    Init;
  ${PHASE}_PCD_DATABASE_UNINIT  Uninit;
} ${PHASE}_PCD_DATABASE;

#define ${PHASE}_NEX_TOKEN_NUMBER (${PHASE}_LOCAL_TOKEN_NUMBER - ${PHASE}_EX_TOKEN_NUMBER)
""")

gEmptyPcdDatabaseAutoGenC = TemplateString("""
${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
  /* ExMapTable */
  {
    {0, 0, 0}
  },
  /* LocalTokenNumberTable */
  {
    0
  },
  /* GuidTable */
  {
    {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}
  },
  /* StringTable */
  { 0 },
  /* SizeTable */
  {
    0, 0
  },
  /* SkuIdTable */
  { 0 },
  ${SYSTEM_SKU_ID_VALUE}
};
""")

gPcdDatabaseAutoGenC = TemplateString("""
${PHASE}_PCD_DATABASE_INIT g${PHASE}PcdDbInit = {
${BEGIN}  { ${INIT_VALUE_UINT64} }, /*  ${INIT_CNAME_DECL_UINT64}_${INIT_GUID_DECL_UINT64}[${INIT_NUMSKUS_DECL_UINT64}] */
${END}
${BEGIN}  ${VARDEF_VALUE_UINT64}, /* ${VARDEF_CNAME_UINT64}_${VARDEF_GUID_UINT64}_VariableDefault_${VARDEF_SKUID_UINT64} */
${END}
${BEGIN}  { ${INIT_VALUE_UINT32} }, /*  ${INIT_CNAME_DECL_UINT32}_${INIT_GUID_DECL_UINT32}[${INIT_NUMSKUS_DECL_UINT32}] */
${END}
${BEGIN}  ${VARDEF_VALUE_UINT32}, /* ${VARDEF_CNAME_UINT32}_${VARDEF_GUID_UINT32}_VariableDefault_${VARDEF_SKUID_UINT32} */
${END}
  /* VPD */
${BEGIN}  { ${VPD_HEAD_VALUE} }, /* ${VPD_HEAD_CNAME_DECL}_${VPD_HEAD_GUID_DECL}[${VPD_HEAD_NUMSKUS_DECL}] */
${END}
  /* ExMapTable */
  {
${BEGIN}    { ${EXMAPPING_TABLE_EXTOKEN}, ${EXMAPPING_TABLE_LOCAL_TOKEN}, ${EXMAPPING_TABLE_GUID_INDEX} },
${END}
  },
  /* LocalTokenNumberTable */
  {
${BEGIN}    offsetof(${PHASE}_PCD_DATABASE, ${TOKEN_INIT}.${TOKEN_CNAME}_${TOKEN_GUID}${VARDEF_HEADER}) | ${TOKEN_TYPE},
${END}
  },
  /* GuidTable */
  {
${BEGIN}    ${GUID_STRUCTURE},
${END}
  },
${BEGIN}  { ${STRING_HEAD_VALUE} }, /* ${STRING_HEAD_CNAME_DECL}_${STRING_HEAD_GUID_DECL}[${STRING_HEAD_NUMSKUS_DECL}] */
${END}
${BEGIN}  /* ${VARIABLE_HEAD_CNAME_DECL}_${VARIABLE_HEAD_GUID_DECL}_Variable_Header[${VARIABLE_HEAD_NUMSKUS_DECL}] */
  {
    ${VARIABLE_HEAD_VALUE}
  },
${END}
 /* StringTable */
${BEGIN}  ${STRING_TABLE_VALUE}, /* ${STRING_TABLE_CNAME}_${STRING_TABLE_GUID} */
${END}
  /* SizeTable */
  {
${BEGIN}    ${SIZE_TABLE_MAXIMUM_LENGTH}, ${SIZE_TABLE_CURRENT_LENGTH}, /* ${SIZE_TABLE_CNAME}_${SIZE_TABLE_GUID} */
${END}
  },
${BEGIN}  { ${INIT_VALUE_UINT16} }, /*  ${INIT_CNAME_DECL_UINT16}_${INIT_GUID_DECL_UINT16}[${INIT_NUMSKUS_DECL_UINT16}] */
${END}
${BEGIN}  ${VARDEF_VALUE_UINT16}, /* ${VARDEF_CNAME_UINT16}_${VARDEF_GUID_UINT16}_VariableDefault_${VARDEF_SKUID_UINT16} */
${END}
${BEGIN}  { ${INIT_VALUE_UINT8} }, /*  ${INIT_CNAME_DECL_UINT8}_${INIT_GUID_DECL_UINT8}[${INIT_NUMSKUS_DECL_UINT8}] */
${END}
${BEGIN}  ${VARDEF_VALUE_UINT8}, /* ${VARDEF_CNAME_UINT8}_${VARDEF_GUID_UINT8}_VariableDefault_${VARDEF_SKUID_UINT8} */
${END}
${BEGIN}  { ${INIT_VALUE_BOOLEAN} }, /*  ${INIT_CNAME_DECL_BOOLEAN}_${INIT_GUID_DECL_BOOLEAN}[${INIT_NUMSKUS_DECL_BOOLEAN}] */
${END}
${BEGIN}  ${VARDEF_VALUE_BOOLEAN}, /* ${VARDEF_CNAME_BOOLEAN}_${VARDEF_GUID_BOOLEAN}_VariableDefault_${VARDEF_SKUID_BOOLEAN} */
${END}
  /* SkuIdTable */
  { ${BEGIN}${SKUID_VALUE}, ${END} },
  ${SYSTEM_SKU_ID_VALUE}
};
""")


## AutoGen File Header Templates
gAutoGenHeaderString = TemplateString("""\
/**
  DO NOT EDIT
  FILE auto-generated
  Module name:
    ${FileName}
  Abstract:       Auto-generated ${FileName} for building module or library.
**/
""")

gAutoGenHPrologueString = TemplateString("""
#ifndef _${File}_${Guid}
#define _${File}_${Guid}

""")

gAutoGenHEpilogueString = """
#endif
"""

## PEI Core Entry Point Templates
gPeiCoreEntryPointPrototype = TemplateString("""
${BEGIN}
VOID
EFIAPI
${Function} (
  IN CONST  EFI_SEC_PEI_HAND_OFF    *SecCoreData,
  IN CONST  EFI_PEI_PPI_DESCRIPTOR  *PpiList,
  IN VOID                           *Context
  );
${END}
""")

gPeiCoreEntryPointString = TemplateString("""
${BEGIN}
VOID
EFIAPI
ProcessModuleEntryPointList (
  IN CONST  EFI_SEC_PEI_HAND_OFF    *SecCoreData,
  IN CONST  EFI_PEI_PPI_DESCRIPTOR  *PpiList,
  IN VOID                           *Context
  )

{
  ${Function} (SecCoreData, PpiList, Context);
}
${END}
""")


## DXE Core Entry Point Templates
gDxeCoreEntryPointPrototype = TemplateString("""
${BEGIN}
VOID
EFIAPI
${Function} (
  IN VOID  *HobStart
  );
${END}
""")

gDxeCoreEntryPointString = TemplateString("""
${BEGIN}
VOID
EFIAPI
ProcessModuleEntryPointList (
  IN VOID  *HobStart
  )

{
  ${Function} (HobStart);
}
${END}
""")

## PEIM Entry Point Templates
gPeimEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  );
${END}
""")

gPeimEntryPointString = [
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  )

{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};
${BEGIN}
EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  )

{
  return ${Function} (FileHandle, PeiServices);
}
${END}
"""),
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT32 _gPeimRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  )

{
  EFI_STATUS  Status;
  EFI_STATUS  CombinedStatus;

  CombinedStatus = EFI_LOAD_ERROR;
${BEGIN}
  Status = ${Function} (FileHandle, PeiServices);
  if (!EFI_ERROR (Status) || EFI_ERROR (CombinedStatus)) {
    CombinedStatus = Status;
  }
${END}
  return CombinedStatus;
}
""")
]

## SMM_CORE Entry Point Templates
gSmmCoreEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE         ImageHandle,
  IN EFI_SYSTEM_TABLE   *SystemTable
  );
${END}
""")

gSmmCoreEntryPointString = TemplateString("""
${BEGIN}
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE         ImageHandle,
  IN EFI_SYSTEM_TABLE   *SystemTable
  )
{
  return ${Function} (ImageHandle, SystemTable);
}
${END}
""")

## DXE SMM Entry Point Templates
gDxeSmmEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );
${END}
""")

gDxeSmmEntryPointString = [
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
static EFI_STATUS  mDriverEntryPointStatus;

VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
    mDriverEntryPointStatus = Status;
  }
  LongJump (&mJumpContext, (UINTN)-1);
  ASSERT (FALSE);
}

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  mDriverEntryPointStatus = EFI_LOAD_ERROR;

${BEGIN}
  if (SetJump (&mJumpContext) == 0) {
    ExitDriver (${Function} (ImageHandle, SystemTable));
    ASSERT (FALSE);
  }
${END}

  return mDriverEntryPointStatus;
}
""")
]

## UEFI Driver Entry Point Templates
gUefiDriverEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );
${END}
""")

gUefiDriverEntryPointString = [
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

${BEGIN}
EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  return ${Function} (ImageHandle, SystemTable);
}
${END}
VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (EFI_ERROR (Status)) {
    ProcessLibraryDestructorList (gImageHandle, gST);
  }
  gBS->Exit (gImageHandle, Status, 0, NULL);
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};
const UINT32 _gDxeRevision = ${PiSpecVersion};

static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
static EFI_STATUS  mDriverEntryPointStatus;

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  mDriverEntryPointStatus = EFI_LOAD_ERROR;
  ${BEGIN}
  if (SetJump (&mJumpContext) == 0) {
    ExitDriver (${Function} (ImageHandle, SystemTable));
    ASSERT (FALSE);
  }
  ${END}
  return mDriverEntryPointStatus;
}

VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
    mDriverEntryPointStatus = Status;
  }
  LongJump (&mJumpContext, (UINTN)-1);
  ASSERT (FALSE);
}
""")
]


## UEFI Application Entry Point Templates
gUefiApplicationEntryPointPrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );
${END}
""")

gUefiApplicationEntryPointString = [
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};

${BEGIN}
EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  return ${Function} (ImageHandle, SystemTable);
}
${END}
VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (EFI_ERROR (Status)) {
    ProcessLibraryDestructorList (gImageHandle, gST);
  }
  gBS->Exit (gImageHandle, Status, 0, NULL);
}
"""),
TemplateString("""
const UINT32 _gUefiDriverRevision = ${UefiSpecVersion};

EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  ${BEGIN}
  if (SetJump (&mJumpContext) == 0) {
    ExitDriver (${Function} (ImageHandle, SystemTable));
    ASSERT (FALSE);
  }
  ${END}
  return mDriverEntryPointStatus;
}

static BASE_LIBRARY_JUMP_BUFFER  mJumpContext;
static EFI_STATUS  mDriverEntryPointStatus = EFI_LOAD_ERROR;

VOID
EFIAPI
ExitDriver (
  IN EFI_STATUS  Status
  )
{
  if (!EFI_ERROR (Status) || EFI_ERROR (mDriverEntryPointStatus)) {
    mDriverEntryPointStatus = Status;
  }
  LongJump (&mJumpContext, (UINTN)-1);
  ASSERT (FALSE);
}
""")
]

## UEFI Unload Image Templates
gUefiUnloadImagePrototype = TemplateString("""
${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle
  );
${END}
""")

gUefiUnloadImageString = [
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};

EFI_STATUS
EFIAPI
ProcessModuleUnloadList (
  IN EFI_HANDLE        ImageHandle
  )
{
  return EFI_SUCCESS;
}
"""),
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};

${BEGIN}
EFI_STATUS
EFIAPI
ProcessModuleUnloadList (
  IN EFI_HANDLE        ImageHandle
  )
{
  return ${Function} (ImageHandle);
}
${END}
"""),
TemplateString("""
GLOBAL_REMOVE_IF_UNREFERENCED const UINT8 _gDriverUnloadImageCount = ${Count};

EFI_STATUS
EFIAPI
ProcessModuleUnloadList (
  IN EFI_HANDLE        ImageHandle
  )
{
  EFI_STATUS  Status;

  Status = EFI_SUCCESS;
${BEGIN}
  if (EFI_ERROR (Status)) {
    ${Function} (ImageHandle);
  } else {
    Status = ${Function} (ImageHandle);
  }
${END}
  return Status;
}
""")
]

gLibraryStructorPrototype = {
'BASE'  : TemplateString("""${BEGIN}
RETURN_STATUS
EFIAPI
${Function} (
  VOID
  );${END}
"""),

'PEI'   : TemplateString("""${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN       EFI_PEI_FILE_HANDLE       FileHandle,
  IN CONST EFI_PEI_SERVICES          **PeiServices
  );${END}
"""),

'DXE'   : TemplateString("""${BEGIN}
EFI_STATUS
EFIAPI
${Function} (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  );${END}
"""),
}

gLibraryStructorCall = {
'BASE'  : TemplateString("""${BEGIN}
  Status = ${Function} ();
  ASSERT_EFI_ERROR (Status);${END}
"""),

'PEI'   : TemplateString("""${BEGIN}
  Status = ${Function} (FileHandle, PeiServices);
  ASSERT_EFI_ERROR (Status);${END}
"""),

'DXE'   : TemplateString("""${BEGIN}
  Status = ${Function} (ImageHandle, SystemTable);
  ASSERT_EFI_ERROR (Status);${END}
"""),
}

## Library Constructor and Destructor Templates
gLibraryString = {
'BASE'  :   TemplateString("""
${BEGIN}${FunctionPrototype}${END}

VOID
EFIAPI
ProcessLibrary${Type}List (
  VOID
  )
{
${BEGIN}  EFI_STATUS  Status;
${FunctionCall}${END}
}
"""),

'PEI'   :   TemplateString("""
${BEGIN}${FunctionPrototype}${END}

VOID
EFIAPI
ProcessLibrary${Type}List (
  IN       EFI_PEI_FILE_HANDLE       FileHandle,
  IN CONST EFI_PEI_SERVICES          **PeiServices
  )
{
${BEGIN}  EFI_STATUS  Status;
${FunctionCall}${END}
}
"""),

'DXE'   :   TemplateString("""
${BEGIN}${FunctionPrototype}${END}

VOID
EFIAPI
ProcessLibrary${Type}List (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
${BEGIN}  EFI_STATUS  Status;
${FunctionCall}${END}
}
"""),
}

gBasicHeaderFile = "Base.h"

gModuleTypeHeaderFile = {
    "BASE"              :   [gBasicHeaderFile],
    "SEC"               :   ["PiPei.h", "Library/DebugLib.h"],
    "PEI_CORE"          :   ["PiPei.h", "Library/DebugLib.h", "Library/PeiCoreEntryPoint.h"],
    "PEIM"              :   ["PiPei.h", "Library/DebugLib.h", "Library/PeimEntryPoint.h"],
    "DXE_CORE"          :   ["PiDxe.h", "Library/DebugLib.h", "Library/DxeCoreEntryPoint.h"],
    "DXE_DRIVER"        :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "DXE_SMM_DRIVER"    :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "DXE_RUNTIME_DRIVER":   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "DXE_SAL_DRIVER"    :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "UEFI_DRIVER"       :   ["Uefi.h",  "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiDriverEntryPoint.h"],
    "UEFI_APPLICATION"  :   ["Uefi.h",  "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiBootServicesTableLib.h", "Library/UefiApplicationEntryPoint.h"],
    "SMM_CORE"          :   ["PiDxe.h", "Library/BaseLib.h", "Library/DebugLib.h", "Library/UefiDriverEntryPoint.h"],
    "USER_DEFINED"      :   [gBasicHeaderFile]
}

## Create code for module PCDs
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#   @param      Pcd         The PCD object
#
def CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd):
    TokenSpaceGuidValue = Pcd.TokenSpaceGuidValue   #Info.GuidList[Pcd.TokenSpaceGuidCName]
    PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
    #
    # Write PCDs
    #
    PcdTokenName = '_PCD_TOKEN_' + Pcd.TokenCName
    if Pcd.Type in gDynamicExPcd:
        TokenNumber = int(Pcd.TokenValue, 0)
    else:
        if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
            EdkLogger.error("build", AUTOGEN_ERROR,
                            "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                            ExtraData="[%s]" % str(Info))
        TokenNumber = PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName]
    AutoGenH.Append('\n#define %s  %d\n' % (PcdTokenName, TokenNumber))

    EdkLogger.debug(EdkLogger.DEBUG_3, "Creating code for " + Pcd.TokenCName + "." + Pcd.TokenSpaceGuidCName)
    if Pcd.Type not in gItemTypeStringDatabase:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))
    if Pcd.DatumType not in gDatumSizeStringDatabase:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))

    DatumSize = gDatumSizeStringDatabase[Pcd.DatumType]
    DatumSizeLib = gDatumSizeStringDatabaseLib[Pcd.DatumType]
    GetModeName = '_PCD_GET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + Pcd.TokenCName
    SetModeName = '_PCD_SET_MODE_' + gDatumSizeStringDatabaseH[Pcd.DatumType] + '_' + Pcd.TokenCName

    if Pcd.Type in gDynamicExPcd:
        AutoGenH.Append('#define %s  LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
        if Pcd.DatumType == 'VOID*':
            AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
        else:
            AutoGenH.Append('#define %s(Value)  LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, Pcd.TokenSpaceGuidCName, PcdTokenName))
    elif Pcd.Type in gDynamicPcd:
        AutoGenH.Append('#define %s  LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
        if Pcd.DatumType == 'VOID*':
            AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
        else:
            AutoGenH.Append('#define %s(Value)  LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
    else:
        PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[Pcd.Type] + '_' + Pcd.TokenCName
        Const = 'const'
        if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
            Const = ''
        Type = ''
        Array = ''
        Value = Pcd.DefaultValue
        Unicode = False
        ValueNumber = 0
        if Pcd.DatumType in ['UINT64', 'UINT32', 'UINT16', 'UINT8']:
            try:
                if Value.upper().startswith('0X'):
                    ValueNumber = int (Value, 16)
                else:
                    ValueNumber = int (Value)
            except:
                EdkLogger.error("build", AUTOGEN_ERROR,
                                "PCD value is not valid dec or hex number for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                ExtraData="[%s]" % str(Info))
            if Pcd.DatumType == 'UINT64':
                if ValueNumber < 0:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                elif ValueNumber >= 0x10000000000000000:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                if not Value.endswith('ULL'):
                    Value += 'ULL'
            elif Pcd.DatumType == 'UINT32':
                if ValueNumber < 0:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                elif ValueNumber >= 0x100000000:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
            elif Pcd.DatumType == 'UINT16':
                if ValueNumber < 0:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                elif ValueNumber >= 0x10000:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
            elif Pcd.DatumType == 'UINT8':
                if ValueNumber < 0:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "PCD can't be set to negative value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
                elif ValueNumber >= 0x100:
                    EdkLogger.error("build", AUTOGEN_ERROR,
                                    "Too large PCD value for datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                    ExtraData="[%s]" % str(Info))
        if Pcd.DatumType == 'VOID*':
            if Pcd.MaxDatumSize == None or Pcd.MaxDatumSize == '':
                EdkLogger.error("build", AUTOGEN_ERROR,
                                "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                                ExtraData="[%s]" % str(Info))

            ArraySize = int(Pcd.MaxDatumSize, 0)
            if Value[0] == '{':
                Type = '(VOID *)'
            else:
                if Value[0] == 'L':
                    Unicode = True
                Value = Value.lstrip('L')   #.strip('"')
                Value = eval(Value)         # translate escape character
                NewValue = '{'
                for Index in range(0,len(Value)):
                    if Unicode:
                        NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ', '
                    else:
                        NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ', '
                if Unicode:
                    ArraySize = ArraySize / 2;

                if ArraySize < (len(Value) + 1):
                    ArraySize = len(Value) + 1
                Value = NewValue + '0 }'
            Array = '[%d]' % ArraySize
        #
        # skip casting for fixed at build since it breaks ARM assembly.
        # Long term we need PCD macros that work in assembly
        #
        elif Pcd.Type != TAB_PCDS_FIXED_AT_BUILD:
            Value = "((%s)%s)" % (Pcd.DatumType, Value)

        if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
            PcdValueName = '_PCD_PATCHABLE_VALUE_' + Pcd.TokenCName
        else:
            PcdValueName = '_PCD_VALUE_' + Pcd.TokenCName
            
        if Pcd.DatumType == 'VOID*':
            #
            # For unicode, UINT16 array will be generated, so the alignment of unicode is guaranteed.
            #
            if Unicode:
                AutoGenH.Append('#define _PCD_PATCHABLE_%s_SIZE %s\n' % (Pcd.TokenCName, Pcd.MaxDatumSize))
                AutoGenH.Append('#define %s  %s%s\n' %(PcdValueName, Type, PcdVariableName))
                AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT16 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
                AutoGenH.Append('extern %s UINT16 %s%s;\n' %(Const, PcdVariableName, Array))
                AutoGenH.Append('#define %s  %s%s\n' %(GetModeName, Type, PcdVariableName))
            else:
                AutoGenH.Append('#define _PCD_PATCHABLE_%s_SIZE %s\n' % (Pcd.TokenCName, Pcd.MaxDatumSize))
                AutoGenH.Append('#define %s  %s%s\n' %(PcdValueName, Type, PcdVariableName))
                AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s UINT8 %s%s = %s;\n' % (Const, PcdVariableName, Array, Value))
                AutoGenH.Append('extern %s UINT8 %s%s;\n' %(Const, PcdVariableName, Array))
                AutoGenH.Append('#define %s  %s%s\n' %(GetModeName, Type, PcdVariableName))
        elif Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
            AutoGenH.Append('#define %s  %s\n' %(PcdValueName, Value))
            AutoGenC.Append('volatile %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
            AutoGenH.Append('extern volatile %s  %s  %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
            AutoGenH.Append('#define %s  %s%s\n' % (GetModeName, Type, PcdVariableName))
        else:
            AutoGenH.Append('#define %s  %s\n' %(PcdValueName, Value))
            AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s %s = %s;\n' %(Const, Pcd.DatumType, PcdVariableName, PcdValueName))
            AutoGenH.Append('extern %s  %s  %s%s;\n' % (Const, Pcd.DatumType, PcdVariableName, Array))
            AutoGenH.Append('#define %s  %s%s\n' % (GetModeName, Type, PcdVariableName))

        if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
            if Pcd.DatumType == 'VOID*':
                AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPatchPcdSetPtr(_gPcd_BinaryPatch_%s, (UINTN)_PCD_PATCHABLE_%s_SIZE, (SizeOfBuffer), (Buffer))\n' % (SetModeName, Pcd.TokenCName, Pcd.TokenCName))
            else:
                AutoGenH.Append('#define %s(Value)  (%s = (Value))\n' % (SetModeName, PcdVariableName))
        else:
            AutoGenH.Append('//#define %s  ASSERT(FALSE)  // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)

## Create code for library module PCDs
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#   @param      Pcd         The PCD object
#
def CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd):
    PcdTokenNumber = Info.PlatformInfo.PcdTokenNumber
    TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
    TokenCName  = Pcd.TokenCName
    TokenSpaceGuidValue = Pcd.TokenSpaceGuidValue   #Info.GuidList[TokenSpaceGuidCName]
    if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in PcdTokenNumber:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "No generated token number for %s.%s\n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))
    TokenNumber = PcdTokenNumber[TokenCName, TokenSpaceGuidCName]

    if Pcd.Type not in gItemTypeStringDatabase:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))
    if Pcd.DatumType not in gDatumSizeStringDatabase:
        EdkLogger.error("build", AUTOGEN_ERROR,
                        "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                        ExtraData="[%s]" % str(Info))

    DatumType   = Pcd.DatumType
    DatumSize   = gDatumSizeStringDatabaseH[DatumType]
    DatumSizeLib= gDatumSizeStringDatabaseLib[DatumType]
    GetModeName = '_PCD_GET_MODE_' + DatumSize + '_' + TokenCName
    SetModeName = '_PCD_SET_MODE_' + DatumSize + '_' + TokenCName

    Type = ''
    Array = ''
    if Pcd.DatumType == 'VOID*':
        Type = '(VOID *)'
        Array = '[]'

    AutoGenH.Append('#define _PCD_TOKEN_%s  %d\n' % (TokenCName, TokenNumber))

    PcdItemType = Pcd.Type
    #if PcdItemType in gDynamicPcd:
    #    PcdItemType = TAB_PCDS_FIXED_AT_BUILD
    #    if (TokenCName, TokenSpaceGuidCName) in Info.PlatformInfo.Platform.Pcds:
    #        PcdItemType  = Info.PlatformInfo.Platform.Pcds[TokenCName, TokenSpaceGuidCName].Type
    if PcdItemType in gDynamicExPcd:
        PcdTokenName = '_PCD_TOKEN_' + TokenCName
        AutoGenH.Append('#define %s  LibPcdGetEx%s(&%s, %s)\n' % (GetModeName, DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
        if DatumType == 'VOID*':
            AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSetEx%s(&%s, %s, (SizeOfBuffer), (Buffer))\n' % (SetModeName,DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
        else:
            AutoGenH.Append('#define %s(Value)  LibPcdSetEx%s(&%s, %s, (Value))\n' % (SetModeName, DatumSizeLib, TokenSpaceGuidCName, PcdTokenName))
    if PcdItemType in gDynamicPcd:
        PcdTokenName = '_PCD_TOKEN_' + TokenCName
        AutoGenH.Append('#define %s  LibPcdGet%s(%s)\n' % (GetModeName, DatumSizeLib, PcdTokenName))
        if DatumType == 'VOID*':
            AutoGenH.Append('#define %s(SizeOfBuffer, Buffer)  LibPcdSet%s(%s, (SizeOfBuffer), (Buffer))\n' %(SetModeName, DatumSizeLib, PcdTokenName))
        else:
            AutoGenH.Append('#define %s(Value)  LibPcdSet%s(%s, (Value))\n' % (SetModeName, DatumSizeLib, PcdTokenName))
    if PcdItemType == TAB_PCDS_PATCHABLE_IN_MODULE:
        PcdVariableName = '_gPcd_' + gItemTypeStringDatabase[TAB_PCDS_PATCHABLE_IN_MODULE] + '_' + TokenCName
        AutoGenH.Append('extern %s _gPcd_BinaryPatch_%s%s;\n' %(DatumType, TokenCName, Array) )
        AutoGenH.Append('#define %s  %s_gPcd_BinaryPatch_%s\n' %(GetModeName, Type, TokenCName))
        AutoGenH.Append('#define %s(Value)  (%s = (Value))\n' % (SetModeName, PcdVariableName))
    if PcdItemType == TAB_PCDS_FIXED_AT_BUILD or PcdItemType == TAB_PCDS_FEATURE_FLAG:
        AutoGenH.Append('extern const %s _gPcd_FixedAtBuild_%s%s;\n' %(DatumType, TokenCName, Array))
        #AutoGenH.Append('#define _PCD_VALUE_%s  _gPcd_FixedAtBuild_%s\n' %(TokenCName, TokenCName))
        AutoGenH.Append('#define %s  %s_gPcd_FixedAtBuild_%s\n' %(GetModeName, Type, TokenCName))
        AutoGenH.Append('//#define %s  ASSERT(FALSE)  // It is not allowed to set value for a FIXED_AT_BUILD PCD\n' % SetModeName)

## Create code for PCD database in DXE or PEI phase
#
#   @param      Platform    The platform object
#   @retval     tuple       Two TemplateString objects for C code and header file,
#                           respectively
#
def CreatePcdDatabasePhaseSpecificAutoGen (Platform, Phase):
    AutoGenC = TemplateString()
    AutoGenH = TemplateString()

    Dict = {
        'PHASE'                         : Phase,
        'GUID_TABLE_SIZE'               : '1',
        'STRING_TABLE_SIZE'             : '1',
        'SKUID_TABLE_SIZE'              : '1',
        'LOCAL_TOKEN_NUMBER_TABLE_SIZE' : '1',
        'LOCAL_TOKEN_NUMBER'            : '0',
        'EXMAPPING_TABLE_SIZE'          : '1',
        'EX_TOKEN_NUMBER'               : '0',
        'SIZE_TABLE_SIZE'               : '2',
        'GUID_TABLE_EMPTY'              : 'TRUE',
        'STRING_TABLE_EMPTY'            : 'TRUE',
        'SKUID_TABLE_EMPTY'             : 'TRUE',
        'DATABASE_EMPTY'                : 'TRUE',
        'EXMAP_TABLE_EMPTY'             : 'TRUE',
        'PCD_DATABASE_UNINIT_EMPTY'     : '  UINT8  dummy; /* PCD_DATABASE_UNINIT is emptry */',
        'SYSTEM_SKU_ID'                 : '  SKU_ID             SystemSkuId;',
        'SYSTEM_SKU_ID_VALUE'           : '0'
    }

    for DatumType in ['UINT64','UINT32','UINT16','UINT8','BOOLEAN', "VOID*"]:
        Dict['VARDEF_CNAME_' + DatumType] = []
        Dict['VARDEF_GUID_' + DatumType]  = []
        Dict['VARDEF_SKUID_' + DatumType] = []
        Dict['VARDEF_VALUE_' + DatumType] = []
        for Init in ['INIT','UNINIT']:
            Dict[Init+'_CNAME_DECL_' + DatumType]   = []
            Dict[Init+'_GUID_DECL_' + DatumType]    = []
            Dict[Init+'_NUMSKUS_DECL_' + DatumType] = []
            Dict[Init+'_VALUE_' + DatumType]        = []

    for Type in ['STRING_HEAD','VPD_HEAD','VARIABLE_HEAD']:
        Dict[Type + '_CNAME_DECL']   = []
        Dict[Type + '_GUID_DECL']    = []
        Dict[Type + '_NUMSKUS_DECL'] = []
        Dict[Type + '_VALUE'] = []

    Dict['STRING_TABLE_INDEX'] = []
    Dict['STRING_TABLE_LENGTH']  = []
    Dict['STRING_TABLE_CNAME'] = []
    Dict['STRING_TABLE_GUID']  = []
    Dict['STRING_TABLE_VALUE'] = []

    Dict['SIZE_TABLE_CNAME'] = []
    Dict['SIZE_TABLE_GUID']  = []
    Dict['SIZE_TABLE_CURRENT_LENGTH']  = []
    Dict['SIZE_TABLE_MAXIMUM_LENGTH']  = []

    Dict['EXMAPPING_TABLE_EXTOKEN'] = []
    Dict['EXMAPPING_TABLE_LOCAL_TOKEN'] = []
    Dict['EXMAPPING_TABLE_GUID_INDEX'] = []

    Dict['GUID_STRUCTURE'] = []

    Dict['SKUID_VALUE'] = []
    Dict['VARDEF_HEADER'] = []
    if Phase == 'DXE':
        Dict['SYSTEM_SKU_ID'] = ''
        Dict['SYSTEM_SKU_ID_VALUE'] = ''

    StringTableIndex = 0
    StringTableSize = 0
    NumberOfLocalTokens = 0
    NumberOfPeiLocalTokens = 0
    NumberOfDxeLocalTokens = 0
    NumberOfExTokens = 0
    NumberOfSizeItems = 0
    GuidList = []

    for Pcd in Platform.DynamicPcdList:
        CName = Pcd.TokenCName
        TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName

        EdkLogger.debug(EdkLogger.DEBUG_3, "PCD: %s %s (%s : %s)" % (CName, TokenSpaceGuidCName, Pcd.Phase, Phase))
        if Pcd.DatumType not in gDatumSizeStringDatabase:
            EdkLogger.error("build", AUTOGEN_ERROR,
                            "Unknown datum type [%s] of PCD %s.%s" % (Pcd.DatumType, Pcd.TokenSpaceGuidCName, Pcd.TokenCName),
                            ExtraData="[%s]" % str(Platform))

        if Pcd.Phase == 'PEI':
            NumberOfPeiLocalTokens += 1
        if Pcd.Phase == 'DXE':
            NumberOfDxeLocalTokens += 1
        if Pcd.Phase != Phase:
            continue

        #
        # TODO: need GetGuidValue() definition
        #
        TokenSpaceGuidStructure = Pcd.TokenSpaceGuidValue
        TokenSpaceGuid = GuidStructureStringToGuidValueName(TokenSpaceGuidStructure)
        if Pcd.Type in gDynamicExPcd:
            if TokenSpaceGuid not in GuidList:
                GuidList += [TokenSpaceGuid]
                Dict['GUID_STRUCTURE'].append(TokenSpaceGuidStructure)
            NumberOfExTokens += 1

        ValueList = []
        StringHeadOffsetList = []
        VpdHeadOffsetList = []
        VariableHeadValueList = []
        Pcd.InitString = 'UNINIT'

        if Pcd.DatumType == 'VOID*':
            Pcd.TokenTypeList = ['PCD_TYPE_STRING']
        elif Pcd.DatumType == 'BOOLEAN':
            Pcd.TokenTypeList = ['PCD_DATUM_TYPE_UINT8']
        else:
            Pcd.TokenTypeList = ['PCD_DATUM_TYPE_' + Pcd.DatumType]

        if len(Pcd.SkuInfoList) > 1:
            Pcd.TokenTypeList += ['PCD_TYPE_SKU_ENABLED']

        for SkuName in Pcd.SkuInfoList:
            Sku = Pcd.SkuInfoList[SkuName]
            SkuId = Sku.SkuId
            if SkuId == None or SkuId == '':
                continue

            if SkuId not in Dict['SKUID_VALUE']:
                Dict['SKUID_VALUE'].append(SkuId)

            SkuIdIndex =   Dict['SKUID_VALUE'].index(SkuId)
            if len(Sku.VariableName) > 0:
                Pcd.TokenTypeList += ['PCD_TYPE_HII']
                Pcd.InitString = 'INIT'
                VariableNameStructure = StringToArray(Sku.VariableName)
                if VariableNameStructure not in Dict['STRING_TABLE_VALUE']:
                    Dict['STRING_TABLE_CNAME'].append(CName)
                    Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)
                    if StringTableIndex == 0:
                        Dict['STRING_TABLE_INDEX'].append('')
                    else:
                        Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)

                    Dict['STRING_TABLE_LENGTH'].append((len(Sku.VariableName) - 3 + 1) * 2)
                    Dict['STRING_TABLE_VALUE'].append(VariableNameStructure)
                    StringTableIndex += 1
                    StringTableSize += (len(Sku.VariableName) - 3 + 1) * 2

                VariableHeadStringIndex = 0
                for Index in range(Dict['STRING_TABLE_VALUE'].index(VariableNameStructure)):
                    VariableHeadStringIndex += Dict['STRING_TABLE_LENGTH'][Index]

                VariableGuidStructure = Sku.VariableGuidValue
                VariableGuid = GuidStructureStringToGuidValueName(VariableGuidStructure)
                if VariableGuid not in GuidList:
                    GuidList += [VariableGuid]
                    Dict['GUID_STRUCTURE'].append(VariableGuidStructure)
                VariableHeadGuidIndex = GuidList.index(VariableGuid)

                if "PCD_TYPE_STRING" in Pcd.TokenTypeList:
                    VariableHeadValueList.append('%d, %d, %s, offsetof(%s_PCD_DATABASE, Init.%s_%s)' %
                                                 (VariableHeadGuidIndex, VariableHeadStringIndex, Sku.VariableOffset,
                                                  Phase, CName, TokenSpaceGuid))
                else:
                    VariableHeadValueList.append('%d, %d, %s, offsetof(%s_PCD_DATABASE, Init.%s_%s_VariableDefault_%s)' %
                                                 (VariableHeadGuidIndex, VariableHeadStringIndex, Sku.VariableOffset,
                                                  Phase, CName, TokenSpaceGuid, SkuIdIndex))
                Dict['VARDEF_CNAME_'+Pcd.DatumType].append(CName)
                Dict['VARDEF_GUID_'+Pcd.DatumType].append(TokenSpaceGuid)
                Dict['VARDEF_SKUID_'+Pcd.DatumType].append(SkuIdIndex)
                if "PCD_TYPE_STRING" in  Pcd.TokenTypeList:
                    Dict['VARDEF_VALUE_' + Pcd.DatumType].append("%s_%s[%d]" % (Pcd.TokenCName, TokenSpaceGuid, SkuIdIndex))
                else:
                    Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.HiiDefaultValue)
            elif Sku.VpdOffset != '':
                Pcd.TokenTypeList += ['PCD_TYPE_VPD']
                Pcd.InitString = 'INIT'
                VpdHeadOffsetList.append(Sku.VpdOffset)
            
          
            if Pcd.DatumType == 'VOID*':
                Pcd.TokenTypeList += ['PCD_TYPE_STRING']
                Pcd.InitString = 'INIT'
                if Sku.HiiDefaultValue != '' and Sku.DefaultValue == '':
                    Sku.DefaultValue = Sku.HiiDefaultValue
                if Sku.DefaultValue != '':
                    NumberOfSizeItems += 1
                    Dict['STRING_TABLE_CNAME'].append(CName)
                    Dict['STRING_TABLE_GUID'].append(TokenSpaceGuid)

                    if StringTableIndex == 0:
                        Dict['STRING_TABLE_INDEX'].append('')
                    else:
                        Dict['STRING_TABLE_INDEX'].append('_%d' % StringTableIndex)
                    if Sku.DefaultValue[0] == 'L':
                        Size = (len(Sku.DefaultValue) - 3 + 1) * 2
                        Dict['STRING_TABLE_VALUE'].append(StringToArray(Sku.DefaultValue))
                    elif Sku.DefaultValue[0] == '"':
                        Size = len(Sku.DefaultValue) - 2 + 1
                        Dict['STRING_TABLE_VALUE'].append(StringToArray(Sku.DefaultValue))
                    elif Sku.DefaultValue[0] == '{':
                        Size = len(Sku.DefaultValue.replace(',',' ').split())
                        Dict['STRING_TABLE_VALUE'].append(Sku.DefaultValue)

                    StringHeadOffsetList.append(str(StringTableSize))
                    Dict['SIZE_TABLE_CNAME'].append(CName)
                    Dict['SIZE_TABLE_GUID'].append(TokenSpaceGuid)
                    Dict['SIZE_TABLE_CURRENT_LENGTH'].append(Size)
                    Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append(Pcd.MaxDatumSize)
                    if Pcd.MaxDatumSize != '':
                        MaxDatumSize = int(Pcd.MaxDatumSize, 0)
                        if MaxDatumSize > Size:
                            Size = MaxDatumSize
                    Dict['STRING_TABLE_LENGTH'].append(Size)
                    StringTableIndex += 1
                    StringTableSize += (Size)
            else:
                if "PCD_TYPE_HII" not in Pcd.TokenTypeList:
                    Pcd.TokenTypeList += ['PCD_TYPE_DATA']
                    if Sku.DefaultValue == 'TRUE':
                        Pcd.InitString = 'INIT'
                    else:
                        try:
                            if int(Sku.DefaultValue, 0) != 0:
                                Pcd.InitString = 'INIT'
                        except:
                            pass
                
                #
                # For UNIT64 type PCD's value, ULL should be append to avoid
                # warning under linux building environment.
                #
                if Pcd.DatumType == "UINT64":
                    ValueList.append(Sku.DefaultValue + "ULL")
                else:
                    ValueList.append(Sku.DefaultValue)

        Pcd.TokenTypeList = list(set(Pcd.TokenTypeList))
        

        if 'PCD_TYPE_HII' in Pcd.TokenTypeList:
            Dict['VARIABLE_HEAD_CNAME_DECL'].append(CName)
            Dict['VARIABLE_HEAD_GUID_DECL'].append(TokenSpaceGuid)
            Dict['VARIABLE_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
            Dict['VARIABLE_HEAD_VALUE'].append('{ %s }\n' % ' },\n    { '.join(VariableHeadValueList))
            Dict['VARDEF_HEADER'].append('_Variable_Header')
        else:
            Dict['VARDEF_HEADER'].append('')
        if 'PCD_TYPE_VPD' in Pcd.TokenTypeList:
            Dict['VPD_HEAD_CNAME_DECL'].append(CName)
            Dict['VPD_HEAD_GUID_DECL'].append(TokenSpaceGuid)
            Dict['VPD_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
            Dict['VPD_HEAD_VALUE'].append('{ %s }' % ' }, { '.join(VpdHeadOffsetList))
        if 'PCD_TYPE_STRING' in Pcd.TokenTypeList:
            Dict['STRING_HEAD_CNAME_DECL'].append(CName)
            Dict['STRING_HEAD_GUID_DECL'].append(TokenSpaceGuid)
            Dict['STRING_HEAD_NUMSKUS_DECL'].append(len(Pcd.SkuInfoList))
            Dict['STRING_HEAD_VALUE'].append(', '.join(StringHeadOffsetList))
        if 'PCD_TYPE_DATA' in Pcd.TokenTypeList:
            Dict[Pcd.InitString+'_CNAME_DECL_'+Pcd.DatumType].append(CName)
            Dict[Pcd.InitString+'_GUID_DECL_'+Pcd.DatumType].append(TokenSpaceGuid)
            Dict[Pcd.InitString+'_NUMSKUS_DECL_'+Pcd.DatumType].append(len(Pcd.SkuInfoList))
            if Pcd.InitString == 'UNINIT':
                Dict['PCD_DATABASE_UNINIT_EMPTY'] = ''
            else:
                Dict[Pcd.InitString+'_VALUE_'+Pcd.DatumType].append(', '.join(ValueList))

    if Phase == 'PEI':
        NumberOfLocalTokens = NumberOfPeiLocalTokens
    if Phase == 'DXE':
        NumberOfLocalTokens = NumberOfDxeLocalTokens

    Dict['TOKEN_INIT']       = ['' for x in range(NumberOfLocalTokens)]
    Dict['TOKEN_CNAME']      = ['' for x in range(NumberOfLocalTokens)]
    Dict['TOKEN_GUID']       = ['' for x in range(NumberOfLocalTokens)]
    Dict['TOKEN_TYPE']       = ['' for x in range(NumberOfLocalTokens)]
    
    for Pcd in Platform.DynamicPcdList:
        CName = Pcd.TokenCName
        TokenSpaceGuidCName = Pcd.TokenSpaceGuidCName
        if Pcd.Phase != Phase:
            continue

        TokenSpaceGuid = GuidStructureStringToGuidValueName(Pcd.TokenSpaceGuidValue) #(Platform.PackageList, TokenSpaceGuidCName))
        GeneratedTokenNumber = Platform.PcdTokenNumber[CName, TokenSpaceGuidCName] - 1
        if Phase == 'DXE':
            GeneratedTokenNumber -= NumberOfPeiLocalTokens

        EdkLogger.debug(EdkLogger.DEBUG_1, "PCD = %s.%s" % (CName, TokenSpaceGuidCName))
        EdkLogger.debug(EdkLogger.DEBUG_1, "phase = %s" % Phase)
        EdkLogger.debug(EdkLogger.DEBUG_1, "GeneratedTokenNumber = %s" % str(GeneratedTokenNumber))

        Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Init'
        if Pcd.InitString == 'UNINIT':
            Dict['TOKEN_INIT'][GeneratedTokenNumber] = 'Uninit'
        Dict['TOKEN_CNAME'][GeneratedTokenNumber] = CName
        Dict['TOKEN_GUID'][GeneratedTokenNumber] = TokenSpaceGuid
        Dict['TOKEN_TYPE'][GeneratedTokenNumber] = ' | '.join(Pcd.TokenTypeList)
        if Pcd.Type in gDynamicExPcd:
            Dict['EXMAPPING_TABLE_EXTOKEN'].append(Pcd.TokenValue)
            if Phase == 'DXE':
                GeneratedTokenNumber += NumberOfPeiLocalTokens
            #
            # Per, PCD architecture specification, PCD Token Number is 1 based and 0 is defined as invalid token number.
            # For each EX type PCD, a PCD Token Number is assigned. When the
            # PCD Driver/PEIM map EX_GUID and EX_TOKEN_NUMBER to the PCD Token Number,
            # the non-EX Protocol/PPI interface can be called to get/set the value. This assumption is made by
            # Pcd Driver/PEIM in MdeModulePkg.
            # Therefore, 1 is added to GeneratedTokenNumber to generate a PCD Token Number before being inserted
            # to the EXMAPPING_TABLE.
            #
            Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append(GeneratedTokenNumber + 1)
            Dict['EXMAPPING_TABLE_GUID_INDEX'].append(GuidList.index(TokenSpaceGuid))

    if GuidList != []:
        Dict['GUID_TABLE_EMPTY'] = 'FALSE'
        Dict['GUID_TABLE_SIZE'] = len(GuidList)
    else:
        Dict['GUID_STRUCTURE'] = [GuidStringToGuidStructureString('00000000-0000-0000-0000-000000000000')]

    if StringTableIndex == 0:
        Dict['STRING_TABLE_INDEX'].append('')
        Dict['STRING_TABLE_LENGTH'].append(1)
        Dict['STRING_TABLE_CNAME'].append('')
        Dict['STRING_TABLE_GUID'].append('')
        Dict['STRING_TABLE_VALUE'].append('{ 0 }')
    else:
        Dict['STRING_TABLE_EMPTY'] = 'FALSE'
        Dict['STRING_TABLE_SIZE'] = StringTableSize

    if Dict['SIZE_TABLE_CNAME'] == []:
        Dict['SIZE_TABLE_CNAME'].append('')
        Dict['SIZE_TABLE_GUID'].append('')
        Dict['SIZE_TABLE_CURRENT_LENGTH'].append(0)
        Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append(0)

    if NumberOfLocalTokens != 0:
        Dict['DATABASE_EMPTY']                = 'FALSE'
        Dict['LOCAL_TOKEN_NUMBER_TABLE_SIZE'] = NumberOfLocalTokens
        Dict['LOCAL_TOKEN_NUMBER']            = NumberOfLocalTokens

    if NumberOfExTokens != 0:
        Dict['EXMAP_TABLE_EMPTY']    = 'FALSE'
        Dict['EXMAPPING_TABLE_SIZE'] = NumberOfExTokens
        Dict['EX_TOKEN_NUMBER']      = NumberOfExTokens
    else:
        Dict['EXMAPPING_TABLE_EXTOKEN'].append(0)
        Dict['EXMAPPING_TABLE_LOCAL_TOKEN'].append(0)
        Dict['EXMAPPING_TABLE_GUID_INDEX'].append(0)

    if NumberOfSizeItems != 0:
        Dict['SIZE_TABLE_SIZE'] = NumberOfSizeItems * 2

    AutoGenH.Append(gPcdDatabaseAutoGenH.Replace(Dict))
    if NumberOfLocalTokens == 0:
        AutoGenC.Append(gEmptyPcdDatabaseAutoGenC.Replace(Dict))
    else:
        AutoGenC.Append(gPcdDatabaseAutoGenC.Replace(Dict))

    return AutoGenH, AutoGenC

## Create code for PCD database
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreatePcdDatabaseCode (Info, AutoGenC, AutoGenH):
    if Info.PcdIsDriver == "":
        return
    if Info.PcdIsDriver not in gPcdPhaseMap:
        EdkLogger.error("build", AUTOGEN_ERROR, "Not supported PcdIsDriver type:%s" % Info.PcdIsDriver,
                        ExtraData="[%s]" % str(Info))

    AutoGenH.Append(gPcdDatabaseCommonAutoGenH)
    AdditionalAutoGenH, AdditionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (Info.PlatformInfo, 'PEI')
    AutoGenH.Append(AdditionalAutoGenH.String)

    Phase = gPcdPhaseMap[Info.PcdIsDriver]
    if Phase == 'PEI':
        AutoGenC.Append(AdditionalAutoGenC.String)

    if Phase == 'DXE':
        AdditionalAutoGenH, AdditionalAutoGenC = CreatePcdDatabasePhaseSpecificAutoGen (Info.PlatformInfo, Phase)
        AutoGenH.Append(AdditionalAutoGenH.String)
        AutoGenC.Append(AdditionalAutoGenC.String)
        AutoGenH.Append(gPcdDatabaseEpilogueAutoGenH)

## Create code for library constructor
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH):
    #
    # Library Constructors
    #
    ConstructorPrototypeString = TemplateString()
    ConstructorCallingString = TemplateString()
    if Info.IsLibrary:
        DependentLibraryList = [Info.Module]
    else:
        DependentLibraryList = Info.DependentLibraryList
    for Lib in DependentLibraryList:
        if len(Lib.ConstructorList) <= 0:
            continue
        Dict = {'Function':Lib.ConstructorList}
        if Lib.ModuleType in ['BASE', 'SEC']:
            ConstructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
            ConstructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
        elif Lib.ModuleType in ['PEI_CORE','PEIM']:
            ConstructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
            ConstructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
        elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
                                'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
            ConstructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
            ConstructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))

    if str(ConstructorPrototypeString) == '':
        ConstructorPrototypeList = []
    else:
        ConstructorPrototypeList = [str(ConstructorPrototypeString)]
    if str(ConstructorCallingString) == '':
        ConstructorCallingList = []
    else:
        ConstructorCallingList = [str(ConstructorCallingString)]

    Dict = {
        'Type'              :   'Constructor',
        'FunctionPrototype' :   ConstructorPrototypeList,
        'FunctionCall'      :   ConstructorCallingList
    }
    if Info.IsLibrary:
        AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
    else:
        if Info.ModuleType in ['BASE', 'SEC']:
            AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
        elif Info.ModuleType in ['PEI_CORE','PEIM']:
            AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
        elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
                                 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
            AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))

## Create code for library destructor
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH):
    #
    # Library Destructors
    #
    DestructorPrototypeString = TemplateString()
    DestructorCallingString = TemplateString()
    if Info.IsLibrary:
        DependentLibraryList = [Info.Module]
    else:
        DependentLibraryList = Info.DependentLibraryList
    for Index in range(len(DependentLibraryList)-1, -1, -1):
        Lib = DependentLibraryList[Index]
        if len(Lib.DestructorList) <= 0:
            continue
        Dict = {'Function':Lib.DestructorList}
        if Lib.ModuleType in ['BASE', 'SEC']:
            DestructorPrototypeString.Append(gLibraryStructorPrototype['BASE'].Replace(Dict))
            DestructorCallingString.Append(gLibraryStructorCall['BASE'].Replace(Dict))
        elif Lib.ModuleType in ['PEI_CORE','PEIM']:
            DestructorPrototypeString.Append(gLibraryStructorPrototype['PEI'].Replace(Dict))
            DestructorCallingString.Append(gLibraryStructorCall['PEI'].Replace(Dict))
        elif Lib.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
                                'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION', 'SMM_CORE']:
            DestructorPrototypeString.Append(gLibraryStructorPrototype['DXE'].Replace(Dict))
            DestructorCallingString.Append(gLibraryStructorCall['DXE'].Replace(Dict))

    if str(DestructorPrototypeString) == '':
        DestructorPrototypeList = []
    else:
        DestructorPrototypeList = [str(DestructorPrototypeString)]
    if str(DestructorCallingString) == '':
        DestructorCallingList = []
    else:
        DestructorCallingList = [str(DestructorCallingString)]

    Dict = {
        'Type'              :   'Destructor',
        'FunctionPrototype' :   DestructorPrototypeList,
        'FunctionCall'      :   DestructorCallingList
    }
    if Info.IsLibrary:
        AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict)
    else:
        if Info.ModuleType in ['BASE', 'SEC']:
            AutoGenC.Append(gLibraryString['BASE'].Replace(Dict))
        elif Info.ModuleType in ['PEI_CORE','PEIM']:
            AutoGenC.Append(gLibraryString['PEI'].Replace(Dict))
        elif Info.ModuleType in ['DXE_CORE','DXE_DRIVER','DXE_SMM_DRIVER','DXE_RUNTIME_DRIVER',
                                 'DXE_SAL_DRIVER','UEFI_DRIVER','UEFI_APPLICATION','SMM_CORE']:
            AutoGenC.Append(gLibraryString['DXE'].Replace(Dict))


## Create code for ModuleEntryPoint
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
        return
    #
    # Module Entry Points
    #
    NumEntryPoints = len(Info.Module.ModuleEntryPointList)
    if 'PI_SPECIFICATION_VERSION' in Info.Module.Specification:
        PiSpecVersion = Info.Module.Specification['PI_SPECIFICATION_VERSION']
    else:
        PiSpecVersion = 0
    if 'UEFI_SPECIFICATION_VERSION' in Info.Module.Specification:
        UefiSpecVersion = Info.Module.Specification['UEFI_SPECIFICATION_VERSION']
    else:
        UefiSpecVersion = 0
    Dict = {
        'Function'       :   Info.Module.ModuleEntryPointList,
        'PiSpecVersion'  :   PiSpecVersion,
        'UefiSpecVersion':   UefiSpecVersion
    }

    if Info.ModuleType in ['PEI_CORE', 'DXE_CORE', 'SMM_CORE']:
        if NumEntryPoints != 1:
            EdkLogger.error(
                "build",
                AUTOGEN_ERROR,
                '%s must have exactly one entry point' % Info.ModuleType,
                File=str(Info),
                ExtraData= ", ".join(Info.Module.ModuleEntryPointList)
                )
    if Info.ModuleType == 'PEI_CORE':
        AutoGenC.Append(gPeiCoreEntryPointString.Replace(Dict))
        AutoGenH.Append(gPeiCoreEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType == 'DXE_CORE':
        AutoGenC.Append(gDxeCoreEntryPointString.Replace(Dict))
        AutoGenH.Append(gDxeCoreEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType == 'SMM_CORE':
        AutoGenC.Append(gSmmCoreEntryPointString.Replace(Dict))
        AutoGenH.Append(gSmmCoreEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType == 'PEIM':
        if NumEntryPoints < 2:
            AutoGenC.Append(gPeimEntryPointString[NumEntryPoints].Replace(Dict))
        else:
            AutoGenC.Append(gPeimEntryPointString[2].Replace(Dict))
        AutoGenH.Append(gPeimEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType in ['DXE_RUNTIME_DRIVER','DXE_DRIVER','DXE_SAL_DRIVER','UEFI_DRIVER']:
        if NumEntryPoints < 2:
            AutoGenC.Append(gUefiDriverEntryPointString[NumEntryPoints].Replace(Dict))
        else:
            AutoGenC.Append(gUefiDriverEntryPointString[2].Replace(Dict))
        AutoGenH.Append(gUefiDriverEntryPointPrototype.Replace(Dict))
    elif Info.ModuleType == 'DXE_SMM_DRIVER':
        if NumEntryPoints == 0:
            AutoGenC.Append(gDxeSmmEntryPointString[0].Replace(Dict))
        else:
            AutoGenC.Append(gDxeSmmEntryPointString[1].Replace(Dict))
        AutoGenH.Append(gDxeSmmEntryPointPrototype.Replace(Dict))    
    elif Info.ModuleType == 'UEFI_APPLICATION':
        if NumEntryPoints < 2:
            AutoGenC.Append(gUefiApplicationEntryPointString[NumEntryPoints].Replace(Dict))
        else:
            AutoGenC.Append(gUefiApplicationEntryPointString[2].Replace(Dict))
        AutoGenH.Append(gUefiApplicationEntryPointPrototype.Replace(Dict))

## Create code for ModuleUnloadImage
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary or Info.ModuleType in ['USER_DEFINED', 'SEC']:
        return
    #
    # Unload Image Handlers
    #
    NumUnloadImage = len(Info.Module.ModuleUnloadImageList)
    Dict = {'Count':NumUnloadImage, 'Function':Info.Module.ModuleUnloadImageList}
    if NumUnloadImage < 2:
        AutoGenC.Append(gUefiUnloadImageString[NumUnloadImage].Replace(Dict))
    else:
        AutoGenC.Append(gUefiUnloadImageString[2].Replace(Dict))
    AutoGenH.Append(gUefiUnloadImagePrototype.Replace(Dict))

## Create code for GUID
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary:
        return

    if Info.ModuleType in ["USER_DEFINED", "BASE"]:
        GuidType = "GUID"
    else:
        GuidType = "EFI_GUID"

    if Info.GuidList:
        AutoGenC.Append("\n// Guids\n")
    #
    # GUIDs
    #
    for Key in Info.GuidList:
        AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.GuidList[Key]))

## Create code for protocol
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary:
        return

    if Info.ModuleType in ["USER_DEFINED", "BASE"]:
        GuidType = "GUID"
    else:
        GuidType = "EFI_GUID"

    if Info.ProtocolList:
        AutoGenC.Append("\n// Protocols\n")
    #
    # Protocol GUIDs
    #
    for Key in Info.ProtocolList:
        AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.ProtocolList[Key]))

## Create code for PPI
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary:
        return

    if Info.ModuleType in ["USER_DEFINED", "BASE"]:
        GuidType = "GUID"
    else:
        GuidType = "EFI_GUID"

    if Info.PpiList:
        AutoGenC.Append("\n// PPIs\n")
    #
    # PPI GUIDs
    #
    for Key in Info.PpiList:
        AutoGenC.Append('GLOBAL_REMOVE_IF_UNREFERENCED %s %s = %s;\n' % (GuidType, Key, Info.PpiList[Key]))

## Create code for PCD
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreatePcdCode(Info, AutoGenC, AutoGenH):
    if Info.IsLibrary:
        if Info.ModulePcdList:
            AutoGenH.Append("\n// PCD definitions\n")
        for Pcd in Info.ModulePcdList:
            CreateLibraryPcdCode(Info, AutoGenC, AutoGenH, Pcd)
    else:
        if Info.ModulePcdList:
            AutoGenH.Append("\n// Definition of PCDs used in this module\n")
            AutoGenC.Append("\n// Definition of PCDs used in this module\n")
        for Pcd in Info.ModulePcdList:
            CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd)

        if Info.LibraryPcdList:
            AutoGenH.Append("\n// Definition of PCDs used in libraries is in AutoGen.c\n")
            AutoGenC.Append("\n// Definition of PCDs used in libraries\n")
        for Pcd in Info.LibraryPcdList:
            CreateModulePcdCode(Info, AutoGenC, AutoGenC, Pcd)
    CreatePcdDatabaseCode(Info, AutoGenC, AutoGenH)

## Create code for unicode string definition
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#   @param      UniGenCFlag     UniString is generated into AutoGen C file when it is set to True
#   @param      UniGenBinBuffer Buffer to store uni string package data
#
def CreateUnicodeStringCode(Info, AutoGenC, AutoGenH, UniGenCFlag, UniGenBinBuffer):
    WorkingDir = os.getcwd()
    os.chdir(Info.WorkspaceDir)

    IncList = [Info.MetaFile.Dir]
    # Get all files under [Sources] section in inf file for EDK-II module
    SrcList = [F for F in Info.SourceFileList]
    if Info.AutoGenVersion < 0x00010005:
        # Get all files under the module directory for EDK-I module
        Cwd = os.getcwd()
        os.chdir(Info.MetaFile.Dir)
        for Root, Dirs, Files in os.walk("."):
            if 'CVS' in Dirs:
                Dirs.remove('CVS')
            if '.svn' in Dirs:
                Dirs.remove('.svn')
            for File in Files:
                File = PathClass(os.path.join(Root, File), Info.MetaFile.Dir)
                if File in SrcList:
                    continue
                SrcList.append(File)
        os.chdir(Cwd)

    if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-c') > -1:
        CompatibleMode = True
    else:
        CompatibleMode = False

    #
    # -s is a temporary option dedicated for building .UNI files with ISO 639-2 lanauge codes of EDK Shell in EDK2
    #
    if 'BUILD' in Info.BuildOption and Info.BuildOption['BUILD']['FLAGS'].find('-s') > -1:
        if CompatibleMode:
            EdkLogger.error("build", AUTOGEN_ERROR,
                            "-c and -s build options should be used exclusively",
                            ExtraData="[%s]" % str(Info))
        ShellMode = True
    else:
        ShellMode = False

    Header, Code = GetStringFiles(Info.UnicodeFileList, SrcList, IncList, ['.uni', '.inf'], Info.Name, CompatibleMode, ShellMode, UniGenCFlag, UniGenBinBuffer)
    if CompatibleMode or UniGenCFlag:
        AutoGenC.Append("\n//\n//Unicode String Pack Definition\n//\n")
        AutoGenC.Append(Code)
        AutoGenC.Append("\n")
    AutoGenH.Append("\n//\n//Unicode String ID\n//\n")
    AutoGenH.Append(Header)
    if CompatibleMode or UniGenCFlag:
        AutoGenH.Append("\n#define STRING_ARRAY_NAME %sStrings\n" % Info.Name)
    os.chdir(WorkingDir)

## Create common code
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateHeaderCode(Info, AutoGenC, AutoGenH):
    # file header
    AutoGenH.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.h'}))
    # header file Prologue
    AutoGenH.Append(gAutoGenHPrologueString.Replace({'File':'AUTOGENH','Guid':Info.Guid.replace('-','_')}))
    if Info.AutoGenVersion >= 0x00010005:
        # header files includes
        AutoGenH.Append("#include <%s>\n" % gBasicHeaderFile)
        if Info.ModuleType in gModuleTypeHeaderFile \
           and gModuleTypeHeaderFile[Info.ModuleType][0] != gBasicHeaderFile:
            AutoGenH.Append("#include <%s>\n" % gModuleTypeHeaderFile[Info.ModuleType][0])
        AutoGenH.Append('\nextern GUID  gEfiCallerIdGuid;\n\n')

        if Info.IsLibrary:
            return

        AutoGenH.Append("#define EFI_CALLER_ID_GUID \\\n  %s\n" % GuidStringToGuidStructureString(Info.Guid))

    if Info.IsLibrary:
        return
    # C file header
    AutoGenC.Append(gAutoGenHeaderString.Replace({'FileName':'AutoGen.c'}))
    if Info.AutoGenVersion >= 0x00010005:
        # C file header files includes
        if Info.ModuleType in gModuleTypeHeaderFile:
            for Inc in gModuleTypeHeaderFile[Info.ModuleType]:
                AutoGenC.Append("#include <%s>\n" % Inc)
        else:
            AutoGenC.Append("#include <%s>\n" % gBasicHeaderFile)

        #
        # Publish the CallerId Guid
        #
        AutoGenC.Append('\nGLOBAL_REMOVE_IF_UNREFERENCED GUID gEfiCallerIdGuid = %s;\n' % GuidStringToGuidStructureString(Info.Guid))

## Create common code for header file
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#
def CreateFooterCode(Info, AutoGenC, AutoGenH):
    AutoGenH.Append(gAutoGenHEpilogueString)

## Create code for a module
#
#   @param      Info        The ModuleAutoGen object
#   @param      AutoGenC    The TemplateString object for C code
#   @param      AutoGenH    The TemplateString object for header file
#   @param      UniGenCFlag     UniString is generated into AutoGen C file when it is set to True
#   @param      UniGenBinBuffer Buffer to store uni string package data
#
def CreateCode(Info, AutoGenC, AutoGenH, StringH, UniGenCFlag, UniGenBinBuffer):
    CreateHeaderCode(Info, AutoGenC, AutoGenH)

    if Info.AutoGenVersion >= 0x00010005:
        CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH)
        CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH)
        CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH)
        CreatePcdCode(Info, AutoGenC, AutoGenH)
        CreateLibraryConstructorCode(Info, AutoGenC, AutoGenH)
        CreateLibraryDestructorCode(Info, AutoGenC, AutoGenH)
        CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH)
        CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH)

    if Info.UnicodeFileList:
        FileName = "%sStrDefs.h" % Info.Name
        StringH.Append(gAutoGenHeaderString.Replace({'FileName':FileName}))
        StringH.Append(gAutoGenHPrologueString.Replace({'File':'STRDEFS', 'Guid':Info.Guid.replace('-','_')}))
        CreateUnicodeStringCode(Info, AutoGenC, StringH, UniGenCFlag, UniGenBinBuffer)
        StringH.Append("\n#endif\n")
        AutoGenH.Append('#include "%s"\n' % FileName)

    CreateFooterCode(Info, AutoGenC, AutoGenH)

    # no generation of AutoGen.c for R8 modules without unicode file
    if Info.AutoGenVersion < 0x00010005 and len(Info.UnicodeFileList) == 0:
        AutoGenC.String = ''

## Create the code file
#
#   @param      FilePath     The path of code file
#   @param      Content      The content of code file
#   @param      IsBinaryFile The flag indicating if the file is binary file or not
#
#   @retval     True        If file content is changed or file doesn't exist
#   @retval     False       If the file exists and the content is not changed
#
def Generate(FilePath, Content, IsBinaryFile):
    return SaveFileOnChange(FilePath, Content, IsBinaryFile)

